package com.econ.powercloud.ems.dal.handler;

import com.econ.powercloud.common.base.facade.util.JacksonUtil;
import com.econ.powercloud.ems.dal.entity.CalCode;
import com.google.common.collect.Lists;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ Description:类型转换器，将数据库中varchar类型的数据转换为list[CalCode]类型的数据
 * @ Author：hgp
 * @ Create:2021-11-15-8:53
 */
@MappedTypes(List.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class StringObjectListHandler implements TypeHandler<List<CalCode>>{
    @Override
    public void setParameter(PreparedStatement ps, int i, List<CalCode> parameter, JdbcType jdbcType) throws SQLException {
        String str = JacksonUtil.toJSONString(parameter);
        ps.setString(i,str);
    }

    @Override
    public List<CalCode> getResult(ResultSet rs, String columnName) throws SQLException {
        String str = rs.getString(columnName);
        return transfer(str);
    }

    @Override
    public List<CalCode> getResult(ResultSet rs, int columnIndex) throws SQLException {
        String str = rs.getString(columnIndex);
        return transfer(str);
    }

    @Override
    public List<CalCode> getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String str = cs.getString(columnIndex);
        return transfer(str);
    }
    private List<CalCode> transfer(String json){
        if(json==null||"".equals(json)){
            return new ArrayList<>();
        }
        List<CalCode> calCodes = JacksonUtil.parseList(json, CalCode.class);
        return calCodes;
    }
}
